import crypto from 'crypto';
import cookie from 'js-cookie';
import { isPlainObject } from '.';
import { isClient, isProd, isStg } from '@/app/utils';
import notification from '@/app/components/hooks/useNotification';
// import { useStore } from "@/store";

let baseURL = '';
const inital = {
  method: 'GET',
  params: null,
  body: null,
  responseType: 'JSON',
};

const env = process.env.NODE_ENV || 'development';
switch (env) {
  case 'development':
    baseURL = 'http://localhost:3003';
    // baseURL = 'https://www.jianli101.com/api';

    break;
  case 'production':
    if (isClient()) {
      if (isProd) {
        baseURL = 'https://www.jianli101.com/api';
      } else {
        baseURL = 'http://10.2.14.196:3003';
      }
    } else {
      if (isProd || isStg) {
        baseURL = 'http://nest-master:3003';
      } else {
        baseURL = 'http://10.2.14.196:3003';
      }
    }
    break;
}
interface RequestConfig extends RequestInit {
  url: string;
  responseType?: string;
  params?: Record<string, any>;
  getResponse?: boolean;
}
export default function request(data: RequestConfig) {
  let { url, ...config } = data;
  if (typeof url !== 'string')
    throw new TypeError('url must be required and of string type');
  config = { ...inital, ...config };
  let {
    method,
    params,
    body,
    headers = {},
    responseType,
    getResponse,
  } = config;
  const { token } = params || {};
  // 处理URL：请求前缀 & 问号参数
  if (!/^http(s?):\/\//i.test(url)) {
    url = baseURL + url;
  }
  if (params != null) {
    delete params.token;
    params = new URLSearchParams(params);
    url += `${url.includes('?') ? '&' : '?'}${params}`;
  }
  if (isPlainObject(body)) {
    headers['Content-Type'] = 'application/json';
    body = JSON.stringify(body);
  }

  const random = Math.random();
  const timestamp = Date.now();
  const app_id = 'jasenahut1234567890~~$%';
  const sign = crypto
    .createHash('md5')
    .update(`${app_id}${timestamp}${random}`)
    .digest('hex');

  // 类似于AXIOS中的请求拦截器，例如：我们每一次发请求都需要携带TOKEN信息
  (headers as any).Authorization = `Bearer ${
    token || cookie.get('baijie_token') || ''
  }`;
  (headers as any).sign = sign;
  (headers as any).random = random;
  (headers as any).timestamp = timestamp;

  // 把config配置成为fetch需要的对象
  config = {
    method: method.toUpperCase(),
    headers,
    mode: 'cors',
    cache: 'no-cache',
  };
  if (/^(POST|PUT|PATCH)$/i.test(method) && body != null) config.body = body;

  // 发送请求
  return fetch(url, config)
    .then(async (response) => {
      // 只要状态码是以2或者3开始的，才是真正的获取成功
      if (getResponse) {
        if (response.status === 401 || response.status === 402) {
          // useStore.setState({ showLogin: true });
          const result = await response.json();
          notification({
            message: '请先登录',
          });
          return;
        } else if (response.status === 500 || response.status === 429) {
          const result = await response.json();
          notification({
            message: result.msg,
          });
          return;
        }
        return response;
      }
      // if (status >= 200 && status < 400) {
      let result;
      switch (responseType.toUpperCase()) {
        case 'JSON':
          result = await response.json();
          if (result.code !== 200) {
            if (isClient()) {
              if (result.code === 401) {
                // useStore.setState({ showLogin: true });
                notification({
                  message: '请先登录',
                });
              } else {
                notification({
                  message: result.msg,
                });
              }
            }
          }
          return Promise.resolve(result);
        case 'TEXT':
          result = await response.text();
          break;
        case 'BLOB':
          result = await response.blob();
          break;
        case 'ARRAYBUFFER':
          result = await response.arrayBuffer();
          break;
      }
      return result;
      // }
    })
    .catch((reason) => {
      if (reason && reason.code === 'STATUS ERROR') {
        // @1 状态码错误
        switch (reason.status) {
          case 400:
            // ...
            break;
          case 401:
            // ...
            break;
          case 404:
            // ...
            break;
        }
      }
      // else if (isClient() && !navigator.onLine) {
      //   // @2 网络中断
      //   // ...
      // }
      // else {
      //   // @3 请求被终止
      //   // ...
      // }
      if (isClient()) {
        notification({
          message: reason.toString(),
        });
      }

      return Promise.reject(reason);
    });
}
